#include "tcp_client.h"
#include <stdexcept>
#include <string.h>

RTSPClient::RTSPClient() : client_fd(-1) {
}

RTSPClient::~RTSPClient() {
    if (client_fd != -1) {
        close(client_fd);
    }
}

void RTSPClient::init(const std::string &ip_address) {
    client_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (client_fd < 0) {
        perror("socket");
        std::cerr << "无法创建套接字" << std::endl;
        throw std::runtime_error("无法创建套接字");
    }
    
    if (inet_pton(AF_INET, ip_address.c_str(), &address.sin_addr) <= 0) {
        std::cerr << "无效的IP地址" << std::endl;
        throw std::runtime_error("无效的IP地址");
    }

    address.sin_family = AF_INET;
    address.sin_port = htons(RTSP_PORT);
    address.sin_addr.s_addr = INADDR_ANY;

    if (connect(client_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("connect");
        close(client_fd);
        std::cerr << "连接失败" << std::endl;
        throw std::runtime_error("连接失败");
    }
}

void RTSPClient::start() {
    handle_server(client_fd);
}

void RTSPClient::handle_server(int new_socket) {
    const char *describe_request = "DESCRIBE rtsp://example.com/media.mp4 RTSP/1.0\r\nCSeq: 1\r\n\r\n";
    send(client_fd, describe_request, strlen(describe_request), 0);
    std::cout << "发送DESCRIBE请求" << std::endl;

    char buffer[1024] = {0};
    read(client_fd, buffer, 1024);
    std::cout << "接收到DESCRIBE响应：" << std::endl;
    std::cout << buffer << std::endl;

    // 创建RTP套接字并接收数据
    int rtp_sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (rtp_sock < 0) {
        std::cerr << "无法创建RTP套接字" << std::endl;
        return;
    }
    struct sockaddr_in rtp_address;
    rtp_address.sin_family = AF_INET;
    rtp_address.sin_addr.s_addr = inet_addr("239.0.0.1");
    rtp_address.sin_port = htons(RTP_PORT);
    bind(rtp_sock, (struct sockaddr *)&rtp_address, sizeof(rtp_address));

    while (true) {
        char rtp_data[1500] = {0};
        recvfrom(rtp_sock, rtp_data, sizeof(rtp_data), 0, NULL, NULL);
        std::cout << "接收到RTP数据包：" << rtp_data << std::endl;
    }
    close(rtp_sock);
}
